<!--
    接单-我的待办&已办页面
    status: '1' // * 操做状态：0-保存，1-任务完成，2-退回，3-转派
-->
<template>
  <el-container>
    <el-header v-if="titleShow" height="36px">
      <header-title style="text-align: center;padding-left: 0px;" :title="$route.meta.title" />
    </el-header>
    <div class="Message">
      <!-- 基本信息 -->
      <TCollapse title="项目基础信息" class="newSty">
        <BasicMessage :prjname-obj="prjnameObj" />
      </TCollapse>
      <!-- 任务单 -->
      <TCollapse title="任务单">
        <div ref="queryFormBox" class="search-flex-box">
          <PmsForm
            ref="formRef"
            v-model="queryParams"
            :form-option="formOption"
            :select-list="dicLists"
          >
            <template #taskDescription>
              <el-input
                v-model="queryParams.taskDescription"
                style="width: 100%;"
                :disabled="true"
                :rows="4"
                type="textarea"
                resize="none"
                placeholder=""
              />
            </template>
          </PmsForm>
        </div>
      </TCollapse>
      <!-- 完成情况 -->
      <TCollapse title="完成情况">
        <div ref="queryFormBoxTwo" class="search-flex-box">
          <PmsForm
            ref="formRef"
            v-model="queryParamsTwo"
            :form-option="formPerformance"
            :select-list="dicLists"
          >
            <template #jobDescription>
              <el-input
                v-model="queryParamsTwo.jobDescription"
                :rows="4"
                :disabled="jobDpDbled"
                maxlength="500"
                type="textarea"
                resize="none"
                placeholder=""
              />
            </template>
          </PmsForm>
        </div>

        <div style="text-align: right;">
          <el-upload
            ref="upload"
            class="upload-demo"
            action=""
            :on-preview="handlePreview"
            :on-change="handleChange"
            :before-remove="beforeRemove"
            :auto-upload="false"
            multiple
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList"
          >
            <div
              style="margin-top: 20px;height: 70px;display: flex;
          flex-direction: column;align-items: center;"
            >

              <el-button size="small" type="primary" class="pms-button-primary" style="margin-bottom: 18px;">上传附件</el-button>
              <div slot="tip" style="color: red;" class="el-el-form-item__label">只能上传1文件，多个文件请压缩后再上传</div>
            </div>
          </el-upload>
        </div>
        <div />
      </TCollapse>
      <!-- 按钮 -->
      <div ref="buttonArr" class="centerBox footerButton">

        <el-button class="pms-button-primary" type="primary" @click="gatherClicK('1')">保存</el-button>
        <el-button class="pms-button-primary" type="primary" @click="gatherClicK('2')">任务完成</el-button>
        <el-button class="pms-button-primary" type="primary" @click="gatherClicK('3')">退回</el-button>
        <el-button class="pms-button-primary" type="primary" @click="gatherClicK('4')">转派</el-button>
        <el-button class="pms-button-primary" type="primary" @click="gatherClicK('5')">升级</el-button>
        <el-button class="pms-button-primary" type="primary" @click="gatherClicK('6')">关闭</el-button>
      </div>
      <!-- 转派弹框 -->
      <SendordersReassignPage
        v-if="ReassignPageVisible"
        ref="nextPage"
        :visible.sync="ReassignPageVisible"
        @doNextEntity="nextPageRes"
      />
      <!-- 升级 -->
      <SendordersReassignPageLeft
        v-if="ReassignPageLeftVisible"
        ref="nextPage"
        :visible.sync="ReassignPageLeftVisible"
        @doNextEntity="nextPageRes"
      />
    </div>
    <!-- 弹框 -->
    <el-dialog
      ref="DialogRef"
      v-dialogDrag
      :close-on-click-modal="false"
      :title="dialogsTitle"
      :visible.sync="dialogs"
      width="50%"
      height="100%"
      modal
      class="pms-dialog"
      :before-close="handleColse"
    >
      <div v-if="ifDialogRef == '2'" class="topOne textAlign">
        <div class="dialogs">
          <div class="dialogsBox1"><span class="dialogsBox11">*</span> 点击【任务完成】后接单人工作完成，请核对”工作简述“</div>
          <div>确认无误后点击【确认】</div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button class="pms-button-primary" size="small" @click="completionOftaskAdd">确 定</el-button>
          <el-button class="pms-button" size="small" @click="cancel">取 消</el-button>
        </div>
      </div>
      <div v-if="ifDialogRef == '3'" class="topTwo textAlign">
        <div class="dialogsBox21">请填写退回原因</div>
        <div class="dialogsBox22"><el-input v-model="textarea" maxlength="500" type="textarea" placeholder="请输入内容" resize="none" :rows="3" /></div>
        <div slot="footer" class="dialog-footer">
          <el-button class="pms-button-primary" size="small" @click="sendAackAdd">确 定</el-button>
          <el-button class="pms-button" size="small" @click="cancel">取 消</el-button>
        </div>
      </div>
      <div v-if="ifDialogRef == '5'" class="topFour textAlign">
        <div class="dialogs">
          <div><span class="dialogsBox11">*</span> 请确认已保存数据</div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button class="pms-button-primary" size="small" @click="fulfilAtaskAdd">确 定</el-button>
          <el-button class="pms-button" size="small" @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 弹框 -->
  </el-container>
</template>

<script>
import HeaderTitle from '@/components/basic/HeaderTitle'

import SendordersReassignPage from '@/views/businessOperation/SendordersReassignPage'
import SendordersReassignPageLeft from '@/views/businessOperation/SendordersReassignPageLeft'
import TCollapse from '@/components/basic/TCollapse.vue'

import BasicMessage from '@/views/businessOperation/basicMessage.vue'
import PmsForm from '@/views/businessOperation/pmsForm'

import { getQueryObject } from '@/utils' // 获取url地址信息
import { getDropdownData } from '@/api/common' // 字典接口
import { getOrderTakingInfo, getProjectInfoByPrjId, submitTDispatchFlow, getWFWorkItem, commonUpload, commonDownload } from '@/api/businessOperation/index' // 列表接口
import { clonePage } from '@/utils'

import { getNextActivities } from '@/api/workFlow'

// 条件配置
const formOption = {
    size: 'mini',
    inline: true,
    labelWidth: '160px',
    itemData: [
        {
            type: 'select',
            prop: 'dispatchType',
            value: '',
            width: '',
            colSpan: 6,
            disabled: true,
            label: '派单类型',
            dicType: 'TDISPATCH_TYPE',
            clearable: true,
            placeholder: '',
            dicProp: {
                label: 'dictName',
                value: 'dictId'
            }
        },
        {
            type: 'input',
            prop: 'deadline',
            value: '',
            width: '',
            colSpan: 6,
            clearable: true,
            disabled: true,
            label: '解决期限'
        },
        {
            type: 'input',
            prop: 'taskTitle',
            value: '',
            width: '',
            colSpan: 12,
            clearable: true,
            disabled: true,
            label: '任务标题'
        },
        {
            type: 'slot',
            prop: 'taskDescription',
            value: '',
            width: '',
            colSpan: 24,
            clearable: true,
            label: '任务描述'
        }
    ]
}

// 条件配置
const formPerformance = {
    size: 'mini',
    inline: true,
    labelWidth: '160px',
    itemData: [
        {
            type: 'slot',
            prop: 'jobDescription',
            value: '',
            width: '',
            colSpan: 24,
            clearable: true,
            label: '工作简述'
        }
    ]
}
export default {
    name: 'AcceptMangeDetail',
    components: {
        TCollapse,
        HeaderTitle,
        BasicMessage,
        SendordersReassignPage,
        SendordersReassignPageLeft,
        PmsForm
        // BackPage
    },
    data() {
        return {
            prjParams: {}, // 页面路由参数集
            workItemObj: {},
            basicList: [], // 基本数据
            nodeList: [], // 存放当前节点
            queryParams: {}, // 任务单数据
            queryParamsTwo: {}, // 完成情况数据
            formPerformance, // 完成情况数据
            formOption, // 查询条件配置项
            dicLists: {}, // 下拉框字典选项集合
            prjnameObj: {}, // 项目名称基本信息
            textarea: '', // 退回原因
            dialogs: false,
            jobDpDbled: false,
            dialogsTitle: '',
            formVal: {}, // 弹框表单
            ifDialogRef: '', // 弹框类型
            ReassignPageVisible: false, // 转派弹框
            ReassignPageLeftVisible: false, // 升级弹框
            dialogUpload: false, // 上传附件弹框
            ruleForm: { paramsFile: '' },
            fileList: [], // 上传附件
            titleShow: true // 默认展示头部信息,综合查询时候不展示
        }
    },
    async created() {
        this.$nextTick(() => {
            this.setHeight(false)
        })

        const { workItemId, type } = getQueryObject()
        this.prjParams = {
            workItemId,
            type
        }
        this.getDictData()
    },
    async mounted() {
      await this.getList() // 获取基本信息
      await this.getWorkItem()

      if (this.prjParams.type === 'done') {
        this.$refs.buttonArr.style.display = 'none'
        this.jobDpDbled = true
      }
    },
    methods: {

        async getWorkItem() {
          await getWFWorkItem({ workItemId: this.prjParams.workItemId }).then(res => {
              if (+res.code !== 200) {
                  return Promise.reject(res)
        }
              this.workItemObj = res.data
            if (this.prjParams.type === 'todo') {
              this.doSearchNextActivity(res.data) // 获取流程节点
            }
          })
        },
        doSearchNextActivity(val) {
          getNextActivities({
            actInsetId: val.activityInstID,
            processInstId: val.processInstID,
            route: ''
          }).then(res => {
            if (+res.code !== 200) {
                  return Promise.reject(res)
        }
            this.nodeList = res.data[0]
          })
        },
        // 查看数据
        async getList() {
            await getOrderTakingInfo({ workItemId: this.prjParams.workItemId }).then(res => {
                if (+res.code !== 200) {
                  return Promise.reject(res)
        }
                this.basicList = res.data
                this.queryParams = res.data.tdispatchInfo
                this.queryParamsTwo.jobDescription = this.basicList.jobDescription
                if (res.data.fileList !== undefined && res.data.fileList.length > 0) {
                   var file = { name: res.data.fileList[0].fileName, url: res.data.fileList[0].fileUrl, id: res.data.fileList[0].fileId }
                   this.fileList = []
                   this.fileList.push(file)
                }
            })
          if (this.basicList.sendType === '2') { // 获取CRM信息
            const crmObj = { prjName: this.basicList.prjName, prjCode: this.basicList.prjId, orgName: this.basicList.orgName }
            this.prjnameObj = crmObj
          } 
           if (this.basicList.prjId) {
            await getProjectInfoByPrjId({ prjId: this.basicList.prjId }).then(res => {
              if (+res.code !== 200) {
                return Promise.reject(res)
              }
                this.prjnameObj = res.data
              })
            }
        },
        async getDictData() {
            const arr = ['TDISPATCH_TYPE']
            const promises = arr.map(item => getDropdownData(item))
            const results = await Promise.all(promises)
            arr.forEach((item, i) => {
                this.$set(this.dicLists, item, results[i].data ?? [])
            })
        },
        // (保存 任务完成 退回 转派 关闭)集合
        async gatherClicK(val) {
            this.ifDialogRef = val
            // 保存== 1
            if (val === '1') {
                console.log(val, '1')
                var prjFile = await this.uploadFile()
                const params = {
                    pmsflowEntityVO: {
                        userIds: null,
                        nextNodeId: null,
                        workItemId: null,
                        opinion: null
                    },
                    id: this.basicList.id,
                    jobDescription: this.queryParamsTwo.jobDescription ? this.queryParamsTwo.jobDescription : '',
                    sendStaff: null,
                    sendCode: this.basicList.sendCode,
                    fileList: [prjFile],
                    status: '0'
                }
                await submitTDispatchFlow(params).then(res => {
                  if (+res.code !== 200) {
                  return Promise.reject(res)
        }
                  this.$message.success('保存成功!')
                  this.getList()
                })
            }
            // 任务完成== 2
            if (val === '2') {
                if (!this.queryParamsTwo.jobDescription) {
                  this.$message.info('请输入工作简述')
                  return
                }
                this.dialogsTitle = '任务完成'
                this.dialogs = true
            }
            // 退回==3
            if (val === '3') {
                console.log('3')
                this.dialogsTitle = '退回'
                this.dialogs = true
            }
            // 转派==4
            if (val === '4') {
                this.ReassignPageVisible = true
                console.log(this.workFlowData, 'this.workFlowData ')
            }
            // 升级
            if (val === '5') {
                this.ReassignPageLeftVisible = true
            }
            // 关闭==6
            if (val === '6') {
              this.fulfilAtaskAdd()
            }
        },
        async uploadFile() {
          var prjFile = {}
          if (this.fileList.length > 0) {
                const params = { file: this.fileList[0].raw }
                if (params.file === undefined) {
                  prjFile = { fileName: this.fileList[0].name, fileId: this.fileList[0].id, fileUrl: this.fileList[0].url }
                  return prjFile
                }
                const formData = new FormData()
                Object.keys(params).forEach(key => formData.append(key, params[key]))
                const { code, data } = await commonUpload(formData)
                 if (code !== '000000') {
                    this.$message({
                      type: 'error',
                      message: '文件上传失败!'
                    })
                    return null
                  }

                  prjFile = { fileName: data[0].file_name, fileId: data[0].file_id, fileUrl: data[0].http_url }
            }
          return prjFile
        },
        // 任务完成
        async completionOftaskAdd() {
            var prjFile = await this.uploadFile()
              const params = {
                pmsflowEntityVO: {
                    userIds: null,
                    nextNodeId: this.nodeList.nodeId,
                    workItemId: this.prjParams.workItemId,
                    opinion: '任务完成'
                },
                id: this.basicList.id,
                jobDescription: this.queryParamsTwo.jobDescription ? this.queryParamsTwo.jobDescription : '',
                sendStaff: null,
                sendCode: this.basicList.sendCode,
                fileList: [prjFile],
                status: '1'
              }
              console.log(params, '-----params----')
              submitTDispatchFlow(params).then(res => {
                if (+res.code !== 200) {
                  return Promise.reject(res)
        }
                this.fulfilAtaskAdd()
              })
        },
        // 退回
        sendAackAdd() {
          console.log(this.workItemObj, 'this.workItemObjthis.workItemObjthis.workItemObj')
            if (!this.textarea) {
              this.$message.info('请输入退回原因')
              return
            }
            const params = {
                pmsflowEntityVO: {
                    userIds: null,
                    nextNodeId: this.nodeList.nodeId,
                    workItemId: this.prjParams.workItemId,
                    opinion: this.textarea
                },
                id: this.basicList.id,
                jobDescription: this.queryParamsTwo.jobDescription ? this.queryParamsTwo.jobDescription : '',
                sendStaff: null,
                status: '2'
              }
              console.log(params)
             submitTDispatchFlow(params).then(res => {
                if (+res.code !== 200) {
                  return Promise.reject(res)
        }
                this.fulfilAtaskAdd()
            })
        },
        // 转派确认
        async nextPageRes(item) {
          console.log(item, 'item')
          var prjFile = await this.uploadFile()
          console.log(prjFile, 'prjFile')
          const params = {
                pmsflowEntityVO: {
                    userIds: item.loginName,
                    nextNodeId: this.nodeList.nodeId,
                    workItemId: this.prjParams.workItemId,
                    opinion: item.opinion
                },
                id: this.basicList.id,
                jobDescription: this.queryParamsTwo.jobDescription ? this.queryParamsTwo.jobDescription : '',
                sendStaff: item.id,
                sendMode: item.sendMode,
                sendCode: this.basicList.sendCode,
                fileList: [prjFile],
                status: '3' // * 操做状态：0-保存，1-任务完成，2-回退，3-转派
              }
              await submitTDispatchFlow(params).then(res => {
                if (+res.code !== 200) {
                  return Promise.reject(res)
        }
                this.fulfilAtaskAdd()
            })
        },
        // 关闭确认
        fulfilAtaskAdd() {
            clonePage()
        },
        // 取消
        cancel() {
            this.textarea = ''
            this.handleColse()
        },
        // 弹框右上角按钮
        handleColse() {
            this.dialogs = false
        },
        // 设置高度
        setHeight(isFold) {
            const child = this.$refs.formRef.$refs
            const height = (formOption.itemData.length / 2).toFixed() - 0
            console.log(child, '🚗')
            // const height = (child.queryFormRef.$children.length / 3).toFixed() - 0
            this.$refs.queryFormBox.style.height = isFold ? `${height * 24}px` : '123px'
            this.$refs.queryFormBoxTwo.style.height = isFold ? `${height * 24}px` : '78px'
            // child.PmsFormRef.style.height = isFold ? `${height * 24}px` : '78px'
        },
        // enableScroll(scrollElement) {
        //     // 移除样式，恢复滚动
        //     scrollElement.style.overflow = 'auto'
        //     scrollElement.style.top = ''
        //     // 恢复之前的滚动位置
        //     window.scrollTo(0, scrollTop)
        // },

        beforeRemove(file, fileList) {
          return this.$confirm(`确定移除 ${ file.name }？`)
        },
        handleChange(file, fs) {
          console.log(file, fs, '-----------------change')
          this.fileList = fs
        },
        handlePreview(file) {
          if (file.url === undefined || file.url === '' || file.url === null) {
            return
          }
          fetch(file.url).then(response => response.blob())
          .then(blob => {
            const url = window.URL.createObjectURL(blob)
            const link = document.createElement('a')
            link.href = url
            link.setAttribute('download', file.name)
            document.body.appendChild(link)
            link.click()
          })
          .catch(error => { console.error(error) })
        },
        handleExceed(files, fileList) {
          console.log(files, 'files------------handleExceed')
          // console.log(fileList, "fileList------------handleExceed")
          this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
        }
        // 关闭弹框
        // dialogClosed() {
        //     const contentBody = window.top.document.body
        //     this.enableScroll(contentBody)
        // }
    }
}
</script>

<style lang="scss" scoped>
    ::v-deep .el-textarea.is-disabled .el-textarea__inner {
        background-color: #f7f7f7;
    }
    .footerButton {
        border: 1px solid #ebeef5;
        margin-bottom: 15px;
        margin-top: 0;
        padding: 20px 0;
        .el-button {
            min-width: 100px;
            height: 24px;
            line-height: 0;
            margin-left: 24px;
        }
    }
    .dialogs {
        border: 1px solid #ebeef5;
        margin-bottom: 20px;
        margin-top: 0;
        padding: 20px 0px;
        font-size: 12px;
    }
    .dialogsBox1 {
        margin-bottom: 10px;
    }
    .dialogsBox11 {
        color: red;
    }
    .dialogsBox21 {
        text-align: justify;
    }
    .dialogsBox22 {
        padding: 10px 0px 20px
    }
    .search-flex-box {
      height: 85px;
    }
    .el-collapse-item__content {
        padding-bottom: 20px;
    }
    .textAlign {
      text-align:center;
    }
    .Message {
      padding: 15px 25px 0px;
      width: 100%;
    }

    ::v-deep .el-col-24 {
        height: 110px;
    }
//     .el-upload-list {
//     margin: 0;
//     padding: 0;
//     list-style: none;
//     height: 100px;
//     width: 85%;
//     float: inline-start;
//     padding-top: 10px;
// }
// ::v-deep .el-upload-list {
//     height: 100px;
//     width: 85%;
//     float: inline-start;
//     padding-top: 10px;
// }
// ::v-deep .el-upload-list__item-name {
//   color: #858689;
//     font-weight: bold;
//     display: block;
//     margin-right: 40px;
//     overflow: hidden;
//     padding-left: 4px;
//     text-overflow: ellipsis;
//     -webkit-transition: color 0.3s;
//     transition: color 0.3s;
//     white-space: nowrap;
// }
</style>
